package com.sqfw.project.wp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.common.utils.poi.ExcelUtil;
import com.sqfw.framework.aspectj.lang.annotation.Log;
import com.sqfw.framework.aspectj.lang.enums.BusinessType;
import com.sqfw.framework.interceptor.annotation.RepeatSubmit;
import com.sqfw.framework.web.controller.BaseController;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.framework.web.page.TableDataInfo;
import com.sqfw.project.utils.AESUtils;
import com.sqfw.project.wp.domain.TSmsSendLog;
import com.sqfw.project.wp.domain.TSmsUser;
import com.sqfw.project.wp.domain.WpInfo;
import com.sqfw.project.wp.service.IWpInfoService;
import com.sqfw.project.wp.service.TSMSSendLogService;
import com.sqfw.project.wp.service.TSmsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

@Api(tags = "短信发送记录")
@RestController
@RequestMapping("/wp/sms_send_log")
public class TSMSSendLogController extends BaseController {

    /**
     * 回复短信接口 加密的秘钥
     */
    @Value("${smgp.sqfwKey}")
    private String sqfwKey;

    /**
     * 5分钟 ：毫秒 five
     */
    private static final Long FIVE_MINUTE_SECOND = 5L * 60 * 1000;


    @Autowired
    private TSMSSendLogService tSmsSendLogService;

    @Autowired
    private TSmsUserService tSmsUserService;

    @Autowired
    private IWpInfoService wpInfoService;

    /**
     * 查询短信发送记录列表
     */
    @ApiOperation("查询短信发送记录列表")
    @PreAuthorize("@ss.hasPermi('wp:sms_send_log:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSmsSendLog tSmsSendLog) {
        LambdaQueryWrapper<TSmsSendLog> listWrapper = tSmsSendLogService.getListWrapper(tSmsSendLog);
        startPage();
        List<TSmsSendLog> list = tSmsSendLogService.list(listWrapper);
        for (TSmsSendLog smsSendLog : list) {
            String receivePhone = smsSendLog.getReceivePhone();
            TSmsUser tSmsUser = new TSmsUser();
            tSmsUser.setMobile(receivePhone);
            LambdaQueryWrapper<TSmsUser> listWrapperUser = tSmsUserService.getListWrapper(tSmsUser);
            List<TSmsUser> lists = tSmsUserService.list(listWrapperUser);
            TSmsUser tSmsUser1 = lists.stream().findAny().orElse(null);
            if (tSmsUser1!=null){
                smsSendLog.setGroupname(tSmsUser1.getGroupname());
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出短信发送记录列表
     */
    @ApiOperation("导出短信发送记录列表")
    @Log(title = "短信发送记录", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('wp:sms_send_log:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, TSmsSendLog tSmsSendLog) {
        LambdaQueryWrapper<TSmsSendLog> listWrapper = tSmsSendLogService.getListWrapper(tSmsSendLog);
        List<TSmsSendLog> list = tSmsSendLogService.list(listWrapper);
        ExcelUtil<TSmsSendLog> util = new ExcelUtil<TSmsSendLog>(TSmsSendLog.class);
        util.exportExcel(response, list, "短信发送记录数据");
    }

    /**
     * 获取短信发送记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('wp:sms_send_log:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tSmsSendLogService.getById(id));
    }

    /**
     * 新增短信发送记录
     */
    @Log(title = "短信发送记录", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('wp:sms_send_log:add')")
    @PostMapping
    public AjaxResult add(@RequestBody @Validated TSmsSendLog tSmsSendLog, HttpServletRequest request) {
        return toAjax(tSmsSendLogService.addSmsSendLog(request, tSmsSendLog));
    }

    /**
     * 修改短信发送记录
     */
    @Log(title = "短信发送记录", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('wp:sms_send_log:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated TSmsSendLog tSmsSendLog) {
        return toAjax(tSmsSendLogService.updateById(tSmsSendLog));
    }

    /**
     * 删除短信发送记录
     */
    @ApiOperation("删除短信发送记录")
    @Log(title = "短信发送记录", businessType = BusinessType.DELETE)
    @PreAuthorize("@ss.hasPermi('wp:sms_send_log:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tSmsSendLogService.removeBatchByIds(Arrays.asList(ids)));
    }

    /**
     * 短信批量发送
     */
    @ApiOperation("短信批量发送")
    @RepeatSubmit
    @Log(title = "短信批量发送", businessType = BusinessType.OTHER)
    @PreAuthorize("@ss.hasPermi('wp:sms_send_log:sendSmsBatch')")
    @PostMapping("/sendSmsBatch")
    public AjaxResult sendSmsBatch(@RequestBody @Validated TSmsSendLog tSmsSendLog, HttpServletRequest request) {
        // 没有传号码，传了通讯录的id
        if (tSmsSendLog.getReceivePhones() == null) {
            TSmsUser tSmsUser = tSmsUserService.getById(tSmsSendLog.getId()); // 通讯录TSmsUser id
            tSmsSendLog.setReceivePhones(tSmsUser.getMobile());
        }
        tSmsSendLogService.sendSmsBatch(request, tSmsSendLog, SecurityUtils.getUsername());
        // tSmsSendLogService.sendSmsBatch("17737112692","查无工单短信");
        return success();
    }


    //-----------------------------政务互联网使用的接口

    /**
     * 接收短信插入日志
     *
     * @param tSmsSendLog
     * @return
     */
    @PostMapping("/recordUpLinkSms")
    public AjaxResult recordUpLinkSms(HttpServletRequest request, @RequestBody TSmsSendLog tSmsSendLog) {
        String token = request.getHeader("token");
        String msg = checkToken(token);
        if (StringUtils.isNotBlank(msg)) {
            return AjaxResult.error(msg);
        }
        tSmsSendLog.setSmType("收");
        tSmsSendLog.setStatus("已收到");
        tSmsSendLog.setSendTime(new Date());

        if (isNumber(tSmsSendLog.getSmContent())) {

            Integer number = Integer.valueOf(tSmsSendLog.getSmContent());

            wpInfoService.updateWpInfoSendSatis(tSmsSendLog.getReceivePhone(), number);
        }


        return AjaxResult.success(tSmsSendLogService.addSmsSendLog(tSmsSendLog));
    }

    public static boolean isNumber(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 进行token检验
     *
     * @param token
     * @return
     */
    private String checkToken(String token) {
        String timestamp = AESUtils.decrypt(token, sqfwKey);
        if (StringUtils.isBlank(timestamp)) {
            return "token解析失败";
        }
        // 毫秒
        long parseTime = Long.parseLong(timestamp);
        long currentTime = System.currentTimeMillis();
        if (currentTime - parseTime > FIVE_MINUTE_SECOND) {
            return "token超过5分钟了";
        }
        return null;
    }

    @PostMapping("/sendSms")
    public AjaxResult sendSms() {
        tSmsSendLogService.sendSms();
        return AjaxResult.success();

    }

}
